#!/usr/bin/python2.4
#
#Copyright 2009 Google Inc.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
#

"""This module provides request handler for admin console dashboard request.

It provides class which displays basic admin dashboard. It also checks whether
to resume on preview version create request.
"""

import re
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import base_request_handler
import constants
import db_utils
import id_encryption


class OddEvenVersions(object):
  """Maintains odd and even numbered versions.

  This class is used for maintaining different list of even and odd versions.
  This is required for displaying the alternate versions in different colors.
  """

  def __init__(self, odd, even):
    self.plain = odd
    self.colored = even


class AdminConsole(base_request_handler.BaseRequestHandler):
  """This is Request handler to serve admin console dashboard.

  This class displays all the currently available versions to the admin. For
  every version, control to publish/delete that version is provided. This
  handler also checks whether the last version create request is to be resumed.
  It may happen during uploading PDF documents one by one.
  """

  def get(self):
    """GET method for this request handler."""
    self._Handler()

  def post(self):
    """POST method for this request handler."""
    self._Handler()

  def _Handler(self):
    """Common handler for GET and POST."""
    db_handler = db_utils.DbHandler()
    versions = db_handler.GetAllVersions()
    versions.sort()
    encrypted_versions = []
    for version_id in versions:
      encrypted_versions.insert(0, id_encryption.Encrypt(version_id))
    # Compute list_of_odd_even_versions array for displaying alternate colored
    # rows in the admin console.
    list_of_odd_even_versions = []
    i = 0
    while i < (len(versions)-1):
      odd_even_version = OddEvenVersions(versions[i], versions[i+1])
      list_of_odd_even_versions.append(odd_even_version)
      i += 2
    if i == (len(versions)-1):
      odd_even_version = OddEvenVersions(versions[i], None)
      list_of_odd_even_versions.append(odd_even_version)

    db_handler.UpdateStatus(constants.GET_METADATA)
    published_version = db_handler.GetPublishedVersion()
    url = self.request.uri
    match = re.search(r'http://([^/]*)/', url)
    base_url = None
    if match:
      base_url = match.group(1).strip()

    if not published_version:
      published_version = 0
    template_values = {
        'versions': list_of_odd_even_versions,
        'published_version': published_version,
        'base_url': base_url,
        'encrypted_versions': encrypted_versions,
        }

    self.response.out.write(self.GenerateHtml('admin.html', template_values))


application = webapp.WSGIApplication([('/', AdminConsole),
                                      ('/admin', AdminConsole)],
                                     debug=True)


def main():
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
